package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    //单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private ApArticleConfigMapper configMapper;

    @Autowired
    private ApArticleContentMapper contentMapper;

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;


    /**
     * 根据参数加载文章列表
     *
     * @param loadtype 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Short loadtype, ArticleHomeDto dto) {
        //1.参数校验，非法侵入情况下不报错
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size =10;
        }
        size=Math.min(size,MAX_PAGE_SIZE);
        dto.setSize(size);

        //类型参数校验

        if(!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_MORE)&&!loadtype.equals(ArticleConstants.LOADTYPE_LOAD_NEW)){
            loadtype=ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //文章频道校验
        if(StringUtils.isEmpty(dto.getTag())){
            dto.setTag(ArticleConstants.DEFAULT_TAP);
        }

        //时间校验
        if(dto.getMaxBehotTime()==null) dto.setMaxBehotTime(new Date());
        if(dto.getMinBehotTime()==null) dto.setMinBehotTime(new Date());
        //2.查询数据
        List<ApArticle> apArticles = apArticleMapper.loadArticleList(dto, loadtype);
        //3.结果封装
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        return responseResult;
    }

    /**
     * 新增三剑客
     * @param
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        if(dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApArticle apArticle=new ApArticle();
        //如果没有id，则表示新增
        if(dto.getId()==null){
        //    1.保存文章信息表
            BeanUtils.copyProperties(dto,apArticle);
            save(apArticle);
        //    2.保存文章配置aparticle_config
            ApArticleConfig config=new ApArticleConfig(apArticle.getId());
            configMapper.insert(config);
        //    3.保存aparticle_content
            ApArticleContent apArticleContent=new ApArticleContent();
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            contentMapper.insert(apArticleContent);
        }else{
        //    如果不是，则修改文章及修改文章内容
            apArticle=getById(dto.getId());
            if(apArticle!=null){
                updateById(apArticle);
            }

        //    先查文章内容，再修改
            ApArticleContent apArticleContent = contentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
            if(apArticleContent!=null){
                apArticleContent.setContent(dto.getContent());
                contentMapper.updateById(apArticleContent);
            }
        }

        //异步调用 生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinIO(apArticle, dto.getContent());
        return ResponseResult.okResult(apArticle.getId()!=null?apArticle.getId():"");
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 文章列表查询plus.查询的就是首页
     *
     * @param dto ,推荐频道  __all__  如果其他频道则是id
     * @param
     * @return
     */
    @Override
    public ResponseResult loadArticleList2(ArticleHomeDto dto) {
        String hotArticleVoListStr =null;
        //1.查询redis
        if(dto.getTag().equals("__all__")){
            hotArticleVoListStr= redisTemplate.opsForValue().get("hot_article_first_page" + dto.getTag());
        }else{//其他频道
            hotArticleVoListStr= redisTemplate.opsForValue().get("hot_article_first_page_" + dto.getTag());
        }

        //2.封装数据
        List<HotArticleVo> articleVoList = JSONArray.parseArray(hotArticleVoListStr, HotArticleVo.class);

        return ResponseResult.okResult(articleVoList);
    }


}
